<template>
  <div class="main-page">
    <!-- 头部导航 -->
    <header class="header">
      <div class="logo">
        <img :src="logoIcon" alt="Logo" class="logo-icon" />
        <span class="logo-text">3D IDEA</span>
      </div>

      <div class="nav-right">
        <!-- 上传按钮：登录后可点击 -->
        <button 
          class="btn-upload" 
          :class="{ 'disabled': !isLoggedIn }"
          :disabled="!isLoggedIn"
          @click="handleUploadClick"
          :title="isLoggedIn ? '上传3D模型' : '请先登录再上传模型'"
        >
          上传模型
        </button>
        
        <!-- 未登录状态：显示登录注册按钮 -->
        <div v-if="!isLoggedIn" class="auth-buttons">
          <button class="btn-login" @click="handleLoginClick">登录</button>
          <button class="btn-register" @click="handleRegisterClick">注册</button>
        </div>
        
        <!-- 已登录状态：显示用户信息和菜单 -->
        <div v-else class="user-section">
          <div class="user-info" @click="toggleUserMenu">
            <span class="username">{{ userDisplayName }}</span>
            <div class="dropdown-arrow" :class="{ 'open': showUserMenu }">▼</div>
          </div>
          
          <!-- 用户下拉菜单 -->
          <div v-if="showUserMenu" class="user-dropdown" @click.stop>
            <div class="dropdown-item user-profile">
              <div class="profile-info">
                <div class="profile-avatar">{{ userDisplayName.charAt(0).toUpperCase() }}</div>
                <div class="profile-details">
                  <div class="profile-name">{{ userDisplayName }}</div>
                  <div class="profile-status">已登录账号</div>
                </div>
              </div>
            </div>
            <div class="dropdown-divider"></div>
            <div class="dropdown-item" @click="handleUserCenter">
              <span>个人中心</span>
            </div>
            <div class="dropdown-item" @click="handleAdminPanel">
              <span>管理后台</span>
            </div>
            <div class="dropdown-item" @click="handleSettings">
              <span>设置</span>
            </div>
            <div class="dropdown-divider"></div>
            <div class="dropdown-item logout" @click="handleLogout">
              <span>退出登录</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 点击空白处关闭菜单 -->
      <div v-if="showUserMenu" class="menu-overlay" @click="closeUserMenu"></div>
    </header>

    <!-- 主页内容 -->
    <div class="main-content">
      <InitIndex @upload-click="handleUploadClick" />
    </div>
    
    <!-- 上传模态框组件 -->
    <UploadModal
      :visible="showUploadModal"
      @close="closeUploadModal"
      @upload-success="handleUploadSuccess"
    />
    
    <!-- 登录模态框组件 -->
    <LoginModal
      :visible="showLoginModal"
      @close="closeLoginModal"
      @login-success="handleLoginSuccess"
      ref="loginModalRef"
    />
    
    <!-- 注册模态框组件 -->
    <RegisterModal
      :visible="showRegisterModal"
      @close="closeRegisterModal"
      @register-success="handleRegisterSuccess"
      ref="registerModalRef"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import logoIcon from '@/assets/3d.svg'
import LoginModal from '@/components/LoginModal.vue'
import RegisterModal from '@/components/RegisterModal.vue'
import UploadModal from '@/components/UploadModal.vue'
import InitIndex from './InitIndex.vue'
import { getToken, setToken, removeToken, getUserInfo, setUserInfo, removeUserInfo } from '@/utils/auth.js'

// 路由实例
const router = useRouter()

// 认证状态管理
const currentUser = ref(null)
const authToken = ref('')

// 计算属性：是否已登录
const isLoggedIn = computed(() => !!authToken.value && !!currentUser.value)

// 计算属性：用户显示名称
const userDisplayName = computed(() => {
  if (!currentUser.value) return ''
  const account = currentUser.value.user || currentUser.value.username || currentUser.value.email || ''
  
  // 格式化手机号：138***5678
  const phoneRegex = /^1[3-9]\d{9}$/
  if (phoneRegex.test(account.replace(/\D/g, ''))) {
    const cleanPhone = account.replace(/\D/g, '')
    return `${cleanPhone.slice(0, 3)}***${cleanPhone.slice(-4)}`
  }
  
  return account
})

// 模态框显示状态
const showUploadModal = ref(false)
const showLoginModal = ref(false)
const showRegisterModal = ref(false)
const showUserMenu = ref(false)

// 组件引用
const loginModalRef = ref()
const registerModalRef = ref()

const handleUploadClick = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录后再上传模型')
    return
  }
  showUploadModal.value = true
}

const handleLoginClick = () => {
  showLoginModal.value = true
}

const handleRegisterClick = () => {
  showRegisterModal.value = true
}

const toggleUserMenu = () => {
  showUserMenu.value = !showUserMenu.value
}

const closeUserMenu = () => {
  showUserMenu.value = false
}

const handleLogout = () => {
  // 清理认证数据
  removeToken()
  removeUserInfo()
  authToken.value = ''
  currentUser.value = null
  
  ElMessage.success('已退出登录')
  closeUserMenu()
}

/**
 * 上传相关事件处理
 */
const closeUploadModal = () => {
  showUploadModal.value = false
}

const handleUploadSuccess = () => {
  // 上传成功后的处理，如果需要刷新首页内容可以在这里添加
  ElMessage.success('上传成功！')
}


/**
 * 登录相关事件处理
 */
const closeLoginModal = () => {
  showLoginModal.value = false
  loginModalRef.value?.resetForm()
}

const handleLoginSuccess = (response) => {
  // 1. 提取token（后端必须返回token字段）
  const token = response.token
  
  // 2. 提取用户信息
  const loginFormData = loginModalRef.value?.loginForm
  const userInfo = {
    id: response.id || response.userId || 1,
    user: loginFormData?.user || response.user || response.username || response.phone || '用户',
    username: response.username || response.displayName || '用户',
    email: response.email || '',
    avatar: response.avatar || '',
    roles: response.roles || ['user'],
    loginTime: new Date().toISOString(),
    ...response
  }
  
  // 3. 保存到localStorage
  setToken(token)
  setUserInfo(userInfo)
  
  // 4. 更新响应式状态
  authToken.value = token
  currentUser.value = userInfo
  
  // 5. 关闭登录框
  closeLoginModal()
  
}

/**
 * 注册相关事件处理
 */
const closeRegisterModal = () => {
  showRegisterModal.value = false
  registerModalRef.value?.resetForm()
}

const handleRegisterSuccess = (userInfo) => {
  closeRegisterModal()
  ElMessage.success('注册成功！请使用您的账号登录。')
}

/**
 * 用户相关事件处理
 */
const handleUserCenter = () => {
  ElMessage.info('个人中心功能正在开发中...')
  closeUserMenu()
}

const handleAdminPanel = () => {
  router.push('/admin')
  closeUserMenu()
}

const handleSettings = () => {
  ElMessage.info('设置功能正在开发中...')
  closeUserMenu()
}

/**
 * 初始化认证状态
 * 
 * 页面加载时从localStorage恢复登录状态
 */
const initializeAuth = () => {
  try {
    const savedToken = getToken()
    const savedUserInfo = getUserInfo()
    
    if (savedToken && savedUserInfo) {
      // 恢复认证状态
      authToken.value = savedToken
      currentUser.value = savedUserInfo
    }
  } catch (error) {
    console.error('初始化认证状态失败:', error)
    // 清理无效数据
    removeToken()
    removeUserInfo()
  }
}

/**
 * 监听键盘事件（ESC键关闭菜单）
 */
const handleKeydown = (event) => {
  if (event.key === 'Escape' && showUserMenu.value) {
    closeUserMenu()
  }
}

/**
 * 页面初始化
 */
onMounted(() => {
  initializeAuth()
  document.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
.main-page {
  min-height: 100vh;
  background: white;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.header {
  padding: 15px 20px;
  border-bottom: 1px solid #e5e5e5;
  display: flex;
  align-items: center;
  justify-content: space-between;
  max-width: 100%;
  margin: 0 auto;
  position: relative;
}

.logo {
  display: flex;
  align-items: center;
  gap: 8px;
}

.logo-icon {
  width: 24px;
  height: 24px;
  filter: invert(20%);
}

.logo-text {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.nav-right {
  display: flex;
  align-items: center;
  gap: 30px;
}

.auth-buttons {
  display: flex;
  gap: 10px;
}

button {
  padding: 10px 20px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid;
}

.btn-upload {
  padding: 12px 24px;
  border: 2px solid #3742fa;
  background: transparent;
  color: #3742fa;
  border-radius: 25px;
  font-size: 16px;
}

.btn-upload:hover:not(.disabled) {
  background: #3742fa;
  color: white;
}

.btn-upload.disabled {
  border-color: #ccc;
  color: #999;
  cursor: not-allowed;
  opacity: 0.6;
}

.btn-back {
  padding: 12px 24px;
  border: 2px solid #28a745;
  background: transparent;
  color: #28a745;
  border-radius: 25px;
  font-size: 16px;
}

.btn-back:hover {
  background: #28a745;
  color: white;
}

.btn-login {
  border-color: #e5e5e5;
  background: transparent;
  color: #333;
}

.btn-login:hover {
  border-color: #3742fa;
  color: #3742fa;
}

.btn-register {
  border-color: #3742fa;
  background: #3742fa;
  color: white;
}

.btn-register:hover {
  background: #2c37ed;
}

.user-section {
  position: relative;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 15px;
  border-radius: 25px;
  border: 1px solid #e5e5e5;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.user-info:hover {
  border-color: #3742fa;
  box-shadow: 0 2px 8px rgba(55, 66, 250, 0.1);
}

.username {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.dropdown-arrow {
  font-size: 10px;
  color: #666;
  transition: transform 0.3s;
}

.dropdown-arrow.open {
  transform: rotate(180deg);
}

.user-dropdown {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 8px;
  background: white;
  border: 1px solid #e5e5e5;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  min-width: 250px;
  z-index: 1000;
  overflow: hidden;
}

.dropdown-item {
  padding: 12px 20px;
  cursor: pointer;
  transition: background-color 0.3s;
  display: flex;
  align-items: center;
  gap: 10px;
}

.dropdown-item:hover:not(.user-profile) {
  background: #f5f5f5;
}

.dropdown-item.logout {
  color: #ff4757;
}

.dropdown-item.logout:hover {
  background: #fff5f5;
}

.user-profile {
  padding: 15px 20px;
  background: #f8f9fa;
  cursor: default;
}

.profile-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.profile-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #3742fa, #5f27cd);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: bold;
}

.profile-details {
  flex: 1;
}

.profile-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 2px;
}

.profile-status {
  font-size: 12px;
  color: #666;
}

.dropdown-divider {
  height: 1px;
  background: #e5e5e5;
  margin: 8px 0;
}

.menu-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  background: transparent;
}

.admin-panel {
  background: #f8f9fa;
  min-height: calc(100vh - 80px);
  padding: 20px 0;
}

/* 主页内容样式 */
.main-content {
  min-height: calc(100vh - 80px);
}

@media (max-width: 768px) {
  .header {
    padding: 10px 15px;
  }
  
  .nav-right {
    gap: 15px;
  }
  
  .username {
    display: none;
  }
  
  .user-dropdown {
    min-width: 200px;
  }
  
  .btn-upload {
    padding: 10px 20px;
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .logo-text {
    display: none;
  }
  
  .nav-right {
    gap: 10px;
  }
  
  .auth-buttons {
    gap: 5px;
  }
  
  .btn-login, .btn-register {
    padding: 8px 16px;
    font-size: 12px;
  }
}
</style>

